package com.nio.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.UUID;

import static io.netty.util.CharsetUtil.UTF_8;

public class MyServerHandler  extends SimpleChannelInboundHandler<ByteBuf> {
    private int count;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        /**/
        byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);

        /*将字节数组转成字符串*/
        String message = new String(buffer, UTF_8);
        System.out.println("服务器接受到数据:"+message);
        System.out.println("服务器接受到消息量:"+(++this.count));

        /*服务器回送数据给客户端，回送一个随机的ID*/
        ByteBuf response = Unpooled.copiedBuffer(UUID.randomUUID().toString()+"\n", UTF_8);
        ctx.writeAndFlush(response);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
